package cn.sangkf.litemall.product.exception;

import cn.sangkf.litemall.common.exception.BizCodeEnum;
import cn.sangkf.litemall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : sangkf
 * @package : cn.sangkf.litemall.product.exception.GlobalControllerAdvice
 * @date : 2020/12/26 下午8:36 星期六
 * @description : TODO
 * @version: 1.0
 * <p>Copyright: Copyright (c) 2020</p>
 */
@Slf4j
@RestControllerAdvice
public class GlobalControllerAdvice {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现文件{}，异常类型：{}", e.getMessage(), e.getClass());
        Map<String, String> errorMap = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach(fieldError -> {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(), BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data", errorMap);
    }


    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        log.error("系统异常{}", e.getMessage());
        e.printStackTrace();
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }

}
